package com.thermofisher.utils;

import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;

@Component
public class AESUtils
{
    @Value("${encrypt.encryptKey}")
    private String encryptKey;

    @Value("${encrypt.decryptKey}")
    private String decryptKey;

    /**
     * 加解密算法/工作模式/填充方式
     */
    private final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";

    public String aesEncrypt(String content) throws Exception
    {
        return base64Encode(aesEncryptToBytes(content, encryptKey));
    }

    public byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception
    {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));
        return cipher.doFinal(content.getBytes("utf-8"));
    }

    public String base64Encode(byte[] bytes)
    {
        return Base64.encodeBase64String(bytes);
    }

    public String aesDecrypt(String encryptStr) throws Exception
    {
        return aesDecryptByBytes(base64Decode(encryptStr), decryptKey);
    }

    public byte[] base64Decode(String base64Code)
    {
        return Base64.decodeBase64(base64Code);
    }

    public String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception
    {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
        byte[] decryptBytes = cipher.doFinal(encryptBytes);
        return new String(decryptBytes);
    }

}
